package com.mmall.service.impl;

import com.google.common.collect.Lists;
import com.mmall.service.IFileService;
import com.mmall.util.FTPUtil;
import org.apache.commons.lang.text.StrBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;

/**
 * @auther Mr.m
 * @date 2019/3/22-14:58
 */
@Service("iFileService")
public class FileServiceimpl implements IFileService {
    private Logger logger = LoggerFactory.getLogger(FileServiceimpl.class);

    public String upLoad(MultipartFile file, String path) {
        if (file == null) {
            return "lalala";
        }
        String fileName = file.getOriginalFilename();
        String fileExtensionName = fileName.substring(fileName.lastIndexOf(".") + 1);
        String upLoadFoleName = UUID.randomUUID().toString() + "." + fileExtensionName;
        logger.info("开始上传文件,上传文件的文件名:{},上传的路径:{},上传文件的新文件名:{}", fileName, path, upLoadFoleName);
        File fileDir = new File(path);
        if (!fileDir.exists()) {
            fileDir.setWritable(true);
            fileDir.mkdirs();
        }
        File targetFile = new File(path, upLoadFoleName);
        try {
            file.transferTo(targetFile);
            //文件已经上传
            //todo 将targetFile上传到ftp服务器
            FTPUtil.upLoadFile(Lists.<File>newArrayList(targetFile));
            //todo 上传完之后，删除upload下的文件
            targetFile.delete();
        } catch (IOException e) {
            logger.error("上传文件异常", e);
            return null;
        }
        return targetFile.getName();
    }
}
